#!/bin/bash

dir=$(cd "$(dirname "$0")"; pwd)
SH_NAME=$0

MAIN_CLASS="com.baoxian.itf.$API_TYPE.StartupManager"

# chkconfig: 2345 93 11
# description:$dir $MAIN_CLASS Server

. /etc/rc.d/init.d/functions

export PATH
PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/data/java/jdk1.6.0_25/bin

enableAutoStart() {
    AutoStartFileName="/etc/init.d/autoStart_${INS_COMPANY}_${API_TYPE}_${BUZZ_TYPE}.sh"
	echo '#!/bin/bash' > $AutoStartFileName
	echo '# chkconfig: 2345 93 11'>>$AutoStartFileName
	echo '# description:services'>>$AutoStartFileName
	echo "cd $dir">>$AutoStartFileName
	echo 'case $1 in'>>$AutoStartFileName
	echo 'start)'>>$AutoStartFileName
	echo "/bin/bash $SH_NAME start" >>$AutoStartFileName
	echo ';;' >>$AutoStartFileName	
	echo 'stop)'>>$AutoStartFileName
	echo "/bin/bash $SH_NAME stop" >>$AutoStartFileName
	echo ';;' >>$AutoStartFileName	
	echo 'restart)'>>$AutoStartFileName
	echo "/bin/bash $SH_NAME restart" >>$AutoStartFileName
	echo ';;' >>$AutoStartFileName
	echo "esac" >>$AutoStartFileName
	chmod +x $AutoStartFileName
	chkconfig --add autoStart_${INS_COMPANY}_${API_TYPE}_${BUZZ_TYPE}.sh
	chkconfig autoStart_${INS_COMPANY}_${API_TYPE}_${BUZZ_TYPE}.sh on
}

start() {
        cd $dir
	mkdir -p /data/log/itf/$API_TYPE/$INS_COMPANY/$BUZZ_TYPE/
#	[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xms1536M -Xmx1536M -Xss1M -XX:MaxPermSize=256M -XX:+UseParallelGC"
	[ -n "$APPCLASSPATH" ] || APPCLASSPATH="$dir/:$dir/*:$dir/dependency/*"
	java $JAVA_OPTS -Dfile.encoding=UTF-8 -cp "$APPCLASSPATH" $MAIN_CLASS >> /data/log/itf/$API_TYPE/$INS_COMPANY/$BUZZ_TYPE/${INS_COMPANY}_${API_TYPE}_${BUZZ_TYPE}.log 2>&1 &
        ret=$?
        if [ $ret -eq 0 ]; then
                action $"Starting $INS_COMPANY $API_TYPE $BUZZ_TYPE $MAIN_CLASS: " /bin/true
		enableAutoStart	
        else
                action $"Starting $INS_COMPANY $API_TYPE $BUZZ_TYPE $MAIN_CLASS: " /bin/false
        fi
}

stop() {
        APP_PID=$(ps -ef |grep $dir |awk '{print $2}' |sed 's/\/java//')
        for i in $APP_PID
        do
            kill -9 $i
            ret=$?
            if [ $ret -eq 0 ]; then
                    action $"Stopping$i $INS_COMPANY $API_TYPE $BUZZ_TYPE $MAIN_CLASS: " /bin/true
            else
                    action $"Stopping$i $INS_COMPANY $API_TYPE $BUZZ_TYPE $MAIN_CLASS: " /bin/false
            fi
        done
}

restart() {

        stop
        sleep 2
        start
}

case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        restart)
                restart
                ;;
        *)
                echo $"Usage: $0 {start|stop|restart}"
                exit 1
		;;
esac
